package generator;

import java.io.FileInputStream;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import cn.luckdou.commons.utils.AliyunOSSClientUtil;
import com.mysql.jdbc.Statement;

public class DBHelper {
	// log日志
	private static Logger logger = Logger.getLogger(AliyunOSSClientUtil.class);
	private static String url;
	private static String user;
	private static String psw;

	static {
		try {
			// 加载配置文件信息 到java对象中
			Properties pro = new Properties();
			// 获取配置文件的绝对路径
			String path = URLDecoder.decode(DBHelper.class.getResource("/config/application.properties").getPath(),
					"utf-8");
			pro.load(new FileInputStream(path));
			url = pro.getProperty("db.master.url");
			user = pro.getProperty("db.master.user");
			psw = pro.getProperty("db.master.password");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static void install(TableInfo tableInfo) throws SQLException {
		Connection conn = getConnection();
		if (null != conn) {
			// String sql = "insert into sys_log (login_name,create_time)
			// values(?,?)";
			// 指定返回生成的主键
			List<Long> ids = new ArrayList<>();
			// 检索由于执行此 Statement 对象而创建的所有自动生成的键
			String sql = "";
			String entityName = tableInfo.getEntityName().substring(0, 1).toLowerCase()
					+ tableInfo.getEntityName().substring(1);
			for (int i = 0; i <= 5; i++) {
				try {

					if (i == 0) {
						sql = "insert  into `sys_resource`(`name`,`url`,`open_mode`,`description`,`icon`,`seq`,`status`,`opened`,`resource_type`,`create_time`,`pid`) values ('"
								+ tableInfo.getComment() + "管理','/admin/" + entityName
								+ "/manager','ajax',NULL,'fi-results',3,0,1,0,NOW(),362)";
					} else if (i == 1) {
						sql = "insert  into `sys_resource`(`name`,`url`,`open_mode`,`description`,`icon`,`pid`,`seq`,`status`,`opened`,`resource_type`,`create_time`) values ('修改','/admin/"
								+ entityName + "/edit','ajax',NULL,'fi-page-edit'," + ids.get(0) + ",1,0,1,1,NOW())";
					} else if (i == 2) {
						sql = "insert  into `sys_resource`(`name`,`url`,`open_mode`,`description`,`icon`,`pid`,`seq`,`status`,`opened`,`resource_type`,`create_time`) values ('删除','/admin/"
								+ entityName + "/delete','ajax',NULL,'fi-page-delete'," + ids.get(0)
								+ ",3,0,1,1,NOW())";
					} else if (i == 3) {
						sql = "insert  into `sys_resource`(`name`,`url`,`open_mode`,`description`,`icon`,`pid`,`seq`,`status`,`opened`,`resource_type`,`create_time`) values ('添加','/admin/"
								+ entityName + "/add','ajax',NULL,'fi-page-add'," + ids.get(0) + ",2,0,1,1,NOW())";
					} else if (i == 4) {
						sql = "insert  into `sys_resource`(`name`,`url`,`open_mode`,`description`,`icon`,`pid`,`seq`,`status`,`opened`,`resource_type`,`create_time`) values ('批量删除','/admin/"
								+ entityName + "/deleteIds','ajax',NULL,'fi-page-delete icon-red'," + ids.get(0)
								+ ",2,0,1,1,NOW())";
					} else {
						continue;
					}
					PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
					pstmt.executeUpdate();
					// 检索由于执行此 Statement 对象而创建的所有自动生成的键
					ResultSet rs = pstmt.getGeneratedKeys();
					if (rs.next()) {
						Long id = rs.getLong(1);
						ids.add(id);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			for (Long resourceId : ids) {
				sql = "INSERT INTO sys_role_resource (role_id, resource_id ) VALUES ('1'," + resourceId + ");";
				PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
				pstmt.executeUpdate();
				// 检索由于执行此 Statement 对象而创建的所有自动生成的键
				ResultSet rs = pstmt.getGeneratedKeys();
				if (rs.next()) {
					Long id = rs.getLong(1);
					logger.info(id);
				}
			}
		}
	}

	/**
	 * public static void install(TableInfo tableInfo) throws SQLException {
	 * Connection conn = getConnection(); if (null != conn) { List<Long> ids =
	 * new ArrayList<>(); SimpleDateFormat sdf=new SimpleDateFormat(
	 * "yyyy-MM-dd HH:mmss"); String sql1 =
	 * "insert  into `resource`(`name`,`url`,`open_mode`,`description`,`icon`,`pid`,`seq`,`status`,`opened`,`resource_type`,`create_time`) values ('"
	 * + tableInfo.getComment() + "管理','/admin/" +
	 * tableInfo.getEntityName().toLowerCase() +
	 * "/manager','ajax',NULL,'fi-results',222,1,0,1,0,'2015-12-01 11:44:20')";
	 * Long pid=0L; String sql2 =
	 * "insert  into `resource`(`name`,`url`,`open_mode`,`description`,`icon`,`pid`,`seq`,`status`,`opened`,`resource_type`,`create_time`) values ('修改','/admin/"
	 * + tableInfo.getEntityName().toLowerCase() +
	 * "/edit','ajax',NULL,'fi-page-edit'," + pid +
	 * ",1,0,1,1,'2015-12-01 11:44:20')"; String sql3 =
	 * "insert  into `resource`(`name`,`url`,`open_mode`,`description`,`icon`,`pid`,`seq`,`status`,`opened`,`resource_type`,`create_time`) values ('添加','/admin/"
	 * + tableInfo.getEntityName().toLowerCase() +
	 * "/add','ajax',NULL,'fi-page-add'," + pid +
	 * ",2,0,1,1,'2015-12-01 11:44:20')"; String sql4 =
	 * "insert  into `resource`(`name`,`url`,`open_mode`,`description`,`icon`,`pid`,`seq`,`status`,`opened`,`resource_type`,`create_time`) values ('删除','/admin/"
	 * + tableInfo.getEntityName().toLowerCase() +
	 * "/delete','ajax',NULL,'fi-page-delete'," + pid +
	 * ",3,0,1,1,'2015-12-01 11:44:20')";
	 * 
	 * for (int i = 1; i < 4; i++) { // 指定返回生成的主键 PreparedStatement pstmt =
	 * conn.prepareStatement("sql" + i, Statement.RETURN_GENERATED_KEYS);
	 * pstmt.executeUpdate(); // 检索由于执行此 Statement 对象而创建的所有自动生成的键 ResultSet rs =
	 * pstmt.getGeneratedKeys(); if (rs.next()) { Long id = rs.getLong(1); if
	 * (i==1) { pid=id; } ids.add(id); System.out.println("数据主键：" + id); } }
	 * 
	 * }
	 * 
	 * }
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
			Properties properties = new Properties();
			properties.put("user", user);
			properties.put("password", psw);
			conn = driver.connect(url, properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
}